import { useCallback, useEffect } from 'react'
import { useStore } from '@renderer/store/useStore'

export default function useCodeSelect() {
  const setData = useStore((state) => state.setData)
  const data = useStore((state) => state.data)
  const setSearchText = useStore((state) => state.setSearchText)
  const searchText = useStore((state) => state.searchText)
  const id = useStore((state) => state.id)
  const setId = useStore((state) => state.setId)

  function scrollElement(id: number) {
    document.getElementById(`result-${id.toString()}`)?.scrollIntoView({
      behavior: 'smooth',
      block: 'center'
    })
  }

  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      switch (e.key) {
        case 'ArrowDown': {
          e.preventDefault()
          if (data.length === 0) return
          const index = data.findIndex((item) => item.id === id)
          const currentId = data[index + 1]?.id ?? data[0].id
          setId(currentId)
          scrollElement(currentId)
          break
        }

        case 'ArrowUp': {
          e.preventDefault()
          if (data.length === 0) return
          const index = data.findIndex((item) => item.id === id)
          const currentId = data[index - 1]?.id ?? data[data.length - 1].id
          setId(currentId)
          scrollElement(currentId)
          break
        }

        case 'Enter': {
          e.preventDefault()
          selectItem(id)
          break
        }
      }
    },
    [data, id]
  )

  async function selectItem(id: number) {
    const findItem = data.find((item) => item.id === id)
    if (findItem) {
      if (findItem.hasOwnProperty('type')) {
        const searchQuery = encodeURIComponent(searchText)
        switch (findItem.type) {
          case 1: {
            const searchUrl = `https://www.google.com/search?q=${searchQuery}`
            window.api.openUrl(searchUrl)
            break
          }
          case 2: {
            const searchUrl = `https://www.baidu.com/s?word=${searchQuery}`
            window.api.openUrl(searchUrl)
            break
          }
          case 3: {
            const searchUrl = `https://cn.bing.com/search?q=${searchQuery}`
            window.api.openUrl(searchUrl)
            break
          }
        }
      } else if (findItem.content.startsWith('http')) {
        window.api.openUrl(findItem.content)
      } else {
        await navigator.clipboard.writeText(findItem.content)
      }
    }
    setData([])
    setSearchText('')
    window.api.hideWindow()
  }

  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [handleKeyDown])
  useEffect(() => {
    setId(data[0]?.id ?? -1)
    if (data.length > 0) {
      const MaxHeight = 582
      const currentHeight = Math.min(MaxHeight, data.length * 74 + 30 + 82)
      window.api.setWindowSize(currentHeight)
    } else {
      window.api.setWindowSize(82)
    }
  }, [data])
  return {
    data,
    id,
    selectItem,
    setId
  }
}
